package com.niannian.db;

import java.io.File;
import java.util.List;
import com.niannian.MyApplication;
import com.niannian.util.Cursor2VO;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

public class DatabaseAccess {

	private static final String DATABASE_NAME = "niannian.db";

	private static final int DATABASE_VERSION = MyApplication.databaseversion;

	private static DatabaseHelper mDbHelper;

	public SQLiteDatabase mDb;

	protected final Context mCtx;

	public DatabaseAccess(Context ctx) {
		this.mCtx = ctx;
	}

	private class DBDialogTask extends AsyncTask<String, Integer, Integer> {

		@Override
		protected Integer doInBackground(String... params) { // 后台进程执行的具体计算在这里实现

			return null;

		}

		@Override
		// 运行于UI线程。如果在doInBackground(Params...)
		// 中使用了publishProgress(Progress...)，就会触发这个方法。在这里可以对进度条控件根据进度值做出具体的响应。
		protected void onProgressUpdate(Integer... values) {

			super.onProgressUpdate(values);

			/*
			 * if (m_pDialog.getMax() != StreamLen)
			 * 
			 * m_pDialog.setMax(StreamLen);
			 * 
			 * m_pDialog.setProgress(values[0]);
			 */

		}

		@Override
		// 执行预处理，它运行于UI线程，可以为后台任务做一些准备工作，比如绘制一个进度条控件。
		protected void onPreExecute() {

			super.onPreExecute();
			// 执行导入数据库以前的操作。

		}

		@Override
		// 运行于UI线程，可以对后台任务的结果做出处理，结果就是doInBackground(Params...)的返回值
		protected void onPostExecute(Integer result) {

			super.onPostExecute(result);
			// 执行导入数据库以后的操作。
			open();

			mDb.execSQL("CREATE TABLE IF NOT EXISTS family_news" + "(id INTEGER NOT NULL DEFAULT 0," + " family INTEGER NOT NULL DEFAULT 0,"
					+ " hasuid INTEGER NOT NULL DEFAULT 0," + " author INTEGER NOT NULL DEFAULT 0," + " author_nickname TEXT NOT NULL DEFAULT '',"
					+ " author_avatar TEXT NOT NULL DEFAULT ''," + " info TEXT NOT NULL DEFAULT ''," + " pic TEXT NOT NULL DEFAULT '',"
					+ " aud TEXT NOT NULL DEFAULT ''," + " news_type TEXT NOT NULL DEFAULT ''," + " created_time INTEGER NOT NULL DEFAULT 0,"
					+ " pic_num INTEGER NOT NULL DEFAULT 0," + " aud_len INTEGER NOT NULL DEFAULT 0," + " PRIMARY KEY(hasuid,id))");

			mDb.execSQL("CREATE TABLE IF NOT EXISTS family_news_comment" + "(id INTEGER NOT NULL DEFAULT 0," + " author INTEGER NOT NULL DEFAULT 0,"
					+ " hasuid INTEGER NOT NULL DEFAULT 0," + " author_nickname TEXT NOT NULL DEFAULT ''," + " post INTEGER NOT NULL DEFAULT 0,"
					+ " author_avatar TEXT NOT NULL DEFAULT ''," + " info TEXT NOT NULL DEFAULT ''," + " aud TEXT NOT NULL DEFAULT '',"
					+ " created_time INTEGER NOT NULL DEFAULT 0," + " aud_len INTEGER NOT NULL DEFAULT 0," + " reply_to INTEGER NOT NULL DEFAULT 0,"
					+ " reply_to_nickname TEXT NOT NULL DEFAULT ''," + " PRIMARY KEY(hasuid,id,post))");

			mDb.execSQL("CREATE TABLE IF NOT EXISTS my_family" + "(id INTEGER NOT NULL DEFAULT 0," + " hasuid INTEGER NOT NULL DEFAULT 0,"
					+ " nickname TEXT NOT NULL DEFAULT ''," + " family INTEGER NOT NULL DEFAULT 0," + " email TEXT NOT NULL DEFAULT '',"
					+ " avatar TEXT NOT NULL DEFAULT ''," + " innername TEXT NOT NULL DEFAULT ''," + " phone TEXT NOT NULL DEFAULT '',"
					+ " birth TEXT NOT NULL DEFAULT ''," + " gender TEXT NOT NULL DEFAULT ''," + " city TEXT NOT NULL DEFAULT '',"
					+ " info_completed INTEGER NOT NULL DEFAULT 0," + " PRIMARY KEY(hasuid,id))");

			mDb.execSQL("CREATE TABLE IF NOT EXISTS greeting_receive" + "(id INTEGER NOT NULL DEFAULT 0," + " hasuid INTEGER NOT NULL DEFAULT 0,"
					+ " author INTEGER NOT NULL DEFAULT 0," + " author_nickname TEXT NOT NULL DEFAULT ''," + " author_avatar TEXT NOT NULL DEFAULT '',"
					+ " author_innername TEXT NOT NULL DEFAULT ''," + " info TEXT NOT NULL DEFAULT ''," + " pic TEXT NOT NULL DEFAULT '',"
					+ " aud TEXT NOT NULL DEFAULT ''," + " aud_len INTEGER NOT NULL DEFAULT 0," + " created_time INTEGER NOT NULL DEFAULT 0,"
					+ " type TEXT NOT NULL DEFAULT ''," + " receiver INTEGER NOT NULL DEFAULT 0," + " receiver_innername TEXT NOT NULL DEFAULT '',"
					+ " receiver_nickname TEXT NOT NULL DEFAULT ''," + " receiver_avatar TEXT NOT NULL DEFAULT ''," + " sent_time INTEGER NOT NULL DEFAULT 0,"
					+ " rtype TEXT NOT NULL DEFAULT ''," + " sender INTEGER NOT NULL DEFAULT 0," + " is_checked TEXT NOT NULL DEFAULT '',"
					+ " reply_by INTEGER NOT NULL DEFAULT 0," + " PRIMARY KEY(hasuid,id))");

			mDb.execSQL("CREATE TABLE IF NOT EXISTS regards_tip" + "(id INTEGER NOT NULL DEFAULT 0," + " hasuid INTEGER NOT NULL DEFAULT 0,"
					+ " creator INTEGER NOT NULL DEFAULT 0," + " title TEXT NOT NULL DEFAULT ''," + " spec_date INTEGER NOT NULL DEFAULT 0,"
					+ " notice_type INTEGER NOT NULL DEFAULT 0," + " desc TEXT NOT NULL DEFAULT ''," + " is_triggered INTEGER NOT NULL DEFAULT 0,"
					+ " is_checked TEXT NOT NULL DEFAULT ''," + " is_f INTEGER NOT NULL DEFAULT 0,"+ "is_order INTEGER NOT NULL DEFAULT 0,"  + " PRIMARY KEY(hasuid,id))");

			mDb.execSQL("CREATE TABLE IF NOT EXISTS news_info" + "(id INTEGER NOT NULL DEFAULT 0," + " hasuid INTEGER NOT NULL DEFAULT 0,"
					+ " author_avatar TEXT NOT NULL DEFAULT ''," + " author_nickname TEXT NOT NULL DEFAULT ''," + " cmt_info TEXT NOT NULL DEFAULT '',"
					+ " cmt_aud TEXT NOT NULL DEFAULT ''," + " cmt_aud_len INTEGER NOT NULL DEFAULT 0," + " post INTEGER NOT NULL DEFAULT 0,"
					+ " post_pic TEXT NOT NULL DEFAULT ''," + " post_info TEXT NOT NULL DEFAULT ''," + " created_time INTEGER NOT NULL DEFAULT 0,"
					+ " news_type INTEGER NOT NULL DEFAULT 2," + " PRIMARY KEY(hasuid,id))");

			mDb.execSQL("CREATE TABLE IF NOT EXISTS systemnews" + "(id INTEGER NOT NULL DEFAULT 0," + " hasuid INTEGER NOT NULL DEFAULT 0,"
					+ " receiver INTEGER NOT NULL DEFAULT 0," + " title TEXT NOT NULL DEFAULT ''," + " desc TEXT NOT NULL DEFAULT '',"
					+ " type TEXT NOT NULL DEFAULT ''," + " is_checked TEXT NOT NULL DEFAULT ''," + " created_time INTEGER NOT NULL DEFAULT 0,"
					+ " PRIMARY KEY(hasuid,id))");

			mDb.execSQL("CREATE TABLE IF NOT EXISTS newss_info" + "(hasuid INTEGER NOT NULL DEFAULT 0," + " msg_count INTEGER NOT NULL DEFAULT 0,"
					+ " sender INTEGER NOT NULL DEFAULT 0," + " msg_type TEXT NOT NULL DEFAULT ''," + " item_time INTEGER NOT NULL DEFAULT 0,"
					+ " item_content TEXT NOT NULL DEFAULT ''," + " sender_avatar TEXT NOT NULL DEFAULT ''," + " sender_nickname TEXT NOT NULL DEFAULT '',"
					+ " PRIMARY KEY(hasuid,sender,msg_type))");

			/* notification表中的targetid，如果type是chat，该值是对应用户uid，其他一律为0，表示是非chat提醒 */
			mDb.execSQL("CREATE TABLE IF NOT EXISTS spm_notification " + "(hasuid INTEGER NOT NULL DEFAULT 0," + " targetid INTEGER NOT NULL DEFAULT 0,"
					+ " targetname TEXT NOT NULL DEFAULT ''," + " lastmsg TEXT NOT NULL DEFAULT ''," + " type TEXT NOT NULL DEFAULT '',"
					+ " unread INTEGER NOT NULL DEFAULT 0," + " dateline INTEGER NOT NULL DEFAULT 0," + " PRIMARY KEY(hasuid,type,targetid))");
			mDb.execSQL("CREATE TABLE IF NOT EXISTS spm_notifydetail" + "(hasuid INTEGER NOT NULL DEFAULT 0," + " nid INTEGER NOT NULL DEFAULT 0,"
					+ " targetid INTEGER NOT NULL DEFAULT 0," + " targetname TEXT NOT NULL DEFAULT ''," + " msg TEXT NOT NULL DEFAULT '',"
					+ " type TEXT NOT NULL DEFAULT ''," + " dateline INTEGER NOT NULL DEFAULT 0," + " PRIMARY KEY(hasuid,nid))");
			close();
			if (onDBInstalledListener != null)

				onDBInstalledListener.OnDBInstalled();

		}

	}

	protected OnDBInstalledListener onDBInstalledListener;

	public void setOnDBInstalledListener(OnDBInstalledListener onDBInstalledListener) {

		this.onDBInstalledListener = onDBInstalledListener;

	}

	public interface OnDBInstalledListener {

		void OnDBInstalled();

	}

	public void InstallDatabase() {
		File dbDir = new File(MyApplication.dbdir);
		if (!dbDir.exists())
			dbDir.mkdir();

		DBDialogTask dialogTask = new DBDialogTask();
		dialogTask.execute(MyApplication.dbdir + "/" + MyApplication.dbfile);
		// File dbfile = new File(MyApplication.dbdir + "/" +
		// MyApplication.dbfile);
		// if (!(dbfile.exists())) {
		// DBDialogTask dialogTask = new DBDialogTask();
		// dialogTask.execute(MyApplication.dbdir + "/" + MyApplication.dbfile);
		// } else {
		// // TODO 判断db文件是否完整
		// open();
		// close();
		// if (onDBInstalledListener != null)
		// onDBInstalledListener.OnDBInstalled();
		// }

	}

	public DatabaseAccess open() throws SQLException {

		if (mDbHelper == null)

			mDbHelper = new DatabaseHelper(mCtx, DATABASE_NAME, DATABASE_VERSION);

		if (mDb == null)

			mDb = mDbHelper.getWritableDatabase();

		if (!mDb.isOpen())

			mDb = mDbHelper.getWritableDatabase();

		return this;

	}

	public void close() {
		mDb.close();
		mDbHelper.close();
	}

	public List executeQuery(String sql, Class clazz) {
		open();
		Cursor cursor = mDb.rawQuery(sql, null);
		if (cursor != null) {
			List tmp = Cursor2VO.cursor2VOList(cursor, clazz);
			close();
			return tmp;
		} else {
			return null;
		}

	}
}
